package com.jf.apply_car.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jf.apply_car.bean.Car;
import com.jf.apply_car.bean.CarImage;
import com.jf.apply_car.mapper.CarImageMapper;
import com.jf.apply_car.mapper.CarMapper;
import com.jf.apply_car.service.CarService;
import com.jf.apply_car.util.BusinessException;
import com.jf.apply_car.util.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CarServiceImpl implements CarService {
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private CarImageMapper carImageMapper;

    public ResultJson getPage(int page, int limit, Car car) {
        PageHelper.startPage(page, limit);
        List<Car> list = carMapper.getAll(car);
        PageInfo<Car> pageInfo = new PageInfo<Car>(list);
        return ResultJson.page(pageInfo.getTotal(), list);
    }

    public ResultJson getById(int carId) {
        return ResultJson.success(carMapper.selectByPrimaryKey(carId));
    }

    public void delete(int[] ids) {
        carMapper.deleteBatch(ids);
        carImageMapper.deleteByCarIds(ids);
    }

    public void saveOrUpdate(Car car) {
        Car search = new Car();
        search.setCarNo(car.getCarNo());
        List<Car> list = carMapper.getAll(search);
        if (!list.isEmpty()) {
            if (car.getCarId() == null) {
                throw new BusinessException("车牌号已存在！");
            }
            Car info = carMapper.selectByPrimaryKey(car.getCarId());
            if (!list.get(0).getCarNo().equals(info.getCarNo())) {
                throw new BusinessException("车牌号已存在！");
            }
        }
        if (car.getCarId() == null) {
            carMapper.insertSelective(car);
        } else {
            carMapper.updateByPrimaryKeySelective(car);
        }

        // 根据汽车id删除相关汽车图片
        carImageMapper.deleteByCarIds(new int[]{car.getCarId()});
        /*封装汽车图片列表*/
        List<CarImage> carImageList = new ArrayList<CarImage>();
        for (String img : car.getCarImages()) {
            CarImage ci = new CarImage();
            ci.setCarId(car.getCarId());
            ci.setUrl(img);

            carImageList.add(ci);
        }
        // 批量添加图片
        carImageMapper.insertBatch(carImageList);
    }

    public ResultJson select() {
        return ResultJson.success(carMapper.getAll(new Car()));
    }
}
